<template>
  <div>
    <card>
      <div slot="header" >
        <div class="m10">
          练习剩余时间：
          <clocker 
            :time="examEndDatetime" 
            format="%H 小时 %M 分 %S 秒	" 
            class="greenColor"
          ></clocker>
        </div>
        <!-- <div class="questionTypeStyle info">
          <label>{{this.questionType}}
          第{{index+1}}题
          剩余{{$store.state.sysconfig.ExerciseQuestionAmount-index-1}}题
          分值:{{questionArray[index].points}}分</label>
        </div> -->
        <div class="questionTypeStyle">
          <label class="info">{{this.questionType}}</label>
          <label class="info">第{{index+1}}题</label>
          <label class="info">剩余{{$store.state.sysconfig.ExerciseQuestionAmount-index-1}}题</label>
          <label class="info">分值:{{questionArray[index].points}}分</label>
        </div>
        <div>
          <x-progress :percent="index+1" :show-cancel="false"></x-progress>
        </div>
      </div >
       <!-- style="height:310px" -->
      <div slot="content">
        <p class="p15" v-text="questionArray[index].question"></p>
        <checklist
          title="选项"
          :options="questionArray[index].content"
          :max="max"
          required
          v-model="questionArray[index].checkedOption"
          @on-change="getQuestionReult"
        ></checklist> 

        <div class="top-line">
          <div class="pl15">
            <span v-show="displayAnswer">
              <span class="info">答案:{{questionArray[index].answer}}</span>
              <span :class="resultStyle" v-show="showAnswer">{{questionResult}}</span>
            </span>
          </div>
          <div class="pr15" v-show="showDisplayAnswerCheckIcon">
              <check-icon :value.sync="displayAnswer" type="default">显示答案</check-icon>
          </div>
        </div>
      </div>
    
      <div slot="footer" class="m15">
        <flexbox>
          <flexbox-item>
            <x-button  
              type="primary"
              text="上一题"
              @click.native="getPrevious"
              plain
            ></x-button>
          </flexbox-item>
          <flexbox-item>
            <x-button 
              type="warn"
              text="结束"
              @click.native="doFinish"
            ></x-button>
          </flexbox-item>
          <flexbox-item>
            <x-button 
              type="primary"
              text="下一题"
              @click.native="getNext"
            ></x-button>
          </flexbox-item>
        </flexbox>
      </div>
    </card>

  </div>
</template>

<script>
import {Card, XButton, Checklist, Clocker, XProgress, CheckIcon, Flexbox, FlexboxItem, dateFormat, stringTrim} from 'vux'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'TheExerciseFrame',
  components: {
    Card,
    XButton,
    Checklist,
    Clocker,
    XProgress,
    CheckIcon,
    Flexbox,
    FlexboxItem,
    dateFormat,
    stringTrim
  },
  data () {
    return {
      index: 0,
      max: 1,
      displayAnswer: false, // 显示答案
      showDisplayAnswerCheckIcon: true, // 显示“显示答案开关”
      resultStyle: '', // 正确/错误样式变量
      questionResult: '', // 做题对错的结果
      showAnswer: false,
      examTimer: {} // 计时器
    }
  },
  // 组件接受的参数有三个：1、题目数组；2、当前索引值（做到那道题了）；3、剩余多少时间
  props: ['questions', 'myindex', 'lastime', 'workType'],
  mounted () {
    console.log('myindex:' + this.myindex)
    console.log('lastime:' + this.lastime)
    console.log('workType:' + this.workType)
    console.log('question:')
    console.log(this.questions)
  },

  methods: {
    ...mapActions(['theExerciseFrameInit']),

    // 根据题行名称（选择题，判断题）获取题型的代码
    // getQuestionCode: function (name) {
    //   var questKV = this.$store.state.questionKV
    //   for (var i = 0; i < questKV.length; i++) {
    //     if (questKV[i].value === name) {
    //       return questKV[i].key
    //     }
    //   }
    // },

    // 即时评判
    getQuestionReult: function () {
      if (this.questionArray[this.index].checkedOption.length !== 0) {
        this.showAnswer = true
        if (stringTrim(this.questionArray[this.index].checkedOption[0]) === stringTrim(this.questionArray[this.index].answer)) {
          this.questionResult = '回答正确'
          this.resultStyle = 'resultStyleSuccess'
        } else {
          this.questionResult = '回答错误'
          this.resultStyle = 'resultStyleFalse'
        }
      }

      // 存储题集(工种代码为名称)
      localStorage.setItem(this.workType, JSON.stringify(this.questionArray))
    },
    // 下一题操作
    getNext: function () {
      this.showAnswer = false
      var that = this
      if (that.index < that.$store.state.sysconfig.ExerciseQuestionAmount) {
        if (that.questionArray[that.index].checkedOption.length === 1) {
          that.index = that.index + 1
        } else {
          that.$vux.alert.show({
            title: '提示',
            content: '请完成本题再继续'
          })
        }
      } else {
        that.$vux.alert.show({
          title: '提示',
          content: '您已完成全部题目'
        })
      }
    },

    // 前一题操作
    getPrevious: function () {
      var that = this
      if (this.index > 0) {
        this.index = this.index - 1
      } else {
        that.$vux.alert.show({
          title: '提示',
          content: '目前已经是第一题了。'
        })
      }
    },

    // 保存已经完成的练习
    doFinish: function () {
      console.log('保持已经完成的练习，工种代码为：' + this.workType)
      var that = this
      var exerciseResult = JSON.parse(localStorage.getItem(this.workType))
      // 正确的个数
      var correctCount = 0
      for (var index = 0; index < exerciseResult.length; index++) {
        if (exerciseResult[index].answer === exerciseResult[index].checkedOption[0]) {
          correctCount += 1
        }
      }
      // 正确率
      var successRate = ((correctCount / exerciseResult.length) * 100).toFixed(0)
      // 用时计算
      var lastTime = localStorage.getItem(this.workType + '-lastMins')
      var totalTime = (this.$store.state.examSets.examMin * 60 - lastTime).toFixed(0)

      var moment = require('moment')
      var questionKey = 'E-' + moment().format('YYYY/MM/DD/hh:mm:ss')
      var history = {
        // 'properties': this.exercisePropertise,
        'correctCount': correctCount, // 正确个数
        'successRate': successRate,   // 正确率
        'totalTime': totalTime,       // 总用时
        'question': JSON.parse(localStorage.getItem(this.workType))
      }
      localStorage.setItem(questionKey, JSON.stringify(history))
      var _this = this
      this.$vux.alert.show({
        title: '练习报告',
        content: '<p>正确：' + correctCount + '题</p><p>正确率：' + successRate + '%</p><p>合计用时：' + ((totalTime > 60) ? parseInt(totalTime / 60) + '分钟' : totalTime + '秒'),
        onHide () {
          clearInterval(_this.examTimer)   // 清空计时器
          localStorage.removeItem(_this.workType + '-lastMins') // 删除本地存储
          localStorage.removeItem(_this.workType) // 删除本地存储
          that.$router.push({name: 'Home'})
        }
      })
    }
  },

  computed: {
    ...mapGetters(['getQuestionCode']),
    // 获取当前题目类型
    questionType: function () {
      if (this.questions.length === 0) {
        return '未知'
      } else {
        if (this.questionArray[this.index].questionType === this.getQuestionCode('判断题')) {
          return '判断题'
        } else {
          return '选择题'
        }
      }
    },

    // 获取题目
    questionArray: function () {
      // 从父组件传递过来的myindex就是起点索引，在这里通过本地变量index获得起点索引后，前后翻，改变本地变量即可
      // 如果改变myindex这个传递过来的值，则会出现警告信息，原则上来讲，从父组件获取的变量是不能改变的
      this.index = this.myindex
      if (this.questions.length === 0) {
        return Array({
          answer: '',
          answerAnalysis: '',
          checkedOption: Array(''),
          content: Array(''),
          createTime: '',
          id: 0,
          points: 0,
          question: '',
          questionType: 10031001,
          updateTime: ''
        })
      } else {
        return this.questions
      }
    },

    // 倒计时结束日期时间
    examEndDatetime: function () {
      console.log('倒计时结束日期时间')
      if (this.lastime !== 0) {
        console.log('时间：' + this.lastime)
        console.log('工种：' + this.workType)
        var lastMins = this.lastime
        var workType = this.workType
        clearInterval(this.examTimer)
        this.examTimer = setInterval(
          () => {
            lastMins -= 1
            localStorage.setItem(workType + '-lastMins', lastMins)
          }, 1000
        )
        // 显示倒计时信息
        var nowTimestamp = Date.parse(new Date())
        var endTimestamp = nowTimestamp + lastMins * 1000
        return dateFormat(new Date(endTimestamp), 'YYYY-MM-DD HH:mm:ss')
      } else {
        clearInterval(this.examTimer)
        return dateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
      }
    }
  },
  created () {
    // this.$nextTick(() => {
    //   this.theExerciseFrameInit()
    // })
    this.theExerciseFrameInit()
  },
  destroyed () {
    console.log('页面关闭的时候执行')
    clearInterval(this.examTimer)
  }
}
</script>

<style scoped>

.questionTypeStyle{
  padding:10px;
  text-align:right;
  border-bottom:1px solid #dfdfdf;
  border-top:1px solid #dfdfdf;
}

.pl15{
  padding:15px;
  float:left;
}
.pr15{
  padding:15px;
  float:right;
}  
.top-line{
  border-top:1px solid #dfdfdf;
}
.m15{
  margin:15px;
}  
.p15{
  padding:15px;
} 
.greenColor{
  color:#179b16;
}
.m10center{
  margin:10px;
  text-align:center;
}
.m10{
  margin:10px;
  font-weight: bold;
}
.ml15{
  margin-left:15px;
}
.mr15{
  margin-right:15px;
}
.resultStyleSuccess{
  padding-top: 2px;
  padding-bottom: 2px;
  padding-left: 2px;
  padding-right: 2px;
  border-radius: 6%;
  border:1px solid #ffffff;
  background-color: #179b16;
  color: #FFF;
}
.resultStyleFalse{
  padding-top: 2px;
  padding-bottom: 2px;
  padding-left: 2px;
  padding-right: 2px;
  border-radius: 6%;
  border:1px solid #ffffff;
  background-color: #E64304;
  color: #FFF;
}
.info{
  padding-top: 2px;
  padding-bottom: 2px;
  padding-left: 3px;
  padding-right: 3px;
  border-radius: 3%;
  border:1px solid #ffffff;
  background-color: #179b16;
  color: #FFF;
}

</style>
